package com.cpr.core.rabbitmq.client;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;
import com.rabbitmq.client.GetResponse;

import java.io.IOException;

/**
 * @author Chen Panrui
 * created at 2022/3/10 14:20
 * mq 推消息的模式
 */
public class HelloConsumeConsumer {

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        // 指定协议 用户名+密码+host+端口号+虚拟主机
        factory.setUri("amqp://admin:123456@106.13.89.7:5672/%2f");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 这行代码：确保mq里面有队列，没有则创建
        channel.queueDeclare("queue.biz", true, false, false, null);

        // 一旦有消息过来，就调用DeliverCallback方法处理消息
        // 通过 consume的方式获取 队列里面的消息，队列里面的消息还会在的，但是通过get的方式获取 队列里面的消息就会拿走不见了
        // 消息deliver的回调函数，消息cancel的回调函数
        channel.basicConsume("queue.biz", new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                System.out.println("推送的消息：" + new String(delivery.getBody()));
            }
        }, new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        });

        //channel.close();
        //connection.close();
    }
}
